<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-menu
            :default-active="activeIndex2"
            class="el-menu-demo"
            mode="horizontal"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b"
            @select="handleSelect"
        >
          <el-menu-item index="0">
            <el-avatar :src="url+userInfo().avatar"></el-avatar>
            <div style="margin-left: 10px;">{{userInfo().name}}</div>
          </el-menu-item>
          <el-menu-item index="1">消息中心</el-menu-item>
          <el-menu-item index="2" :disabled="showEnd">后台信息管理</el-menu-item>
          <el-menu-item index="4" style="margin-left: auto">
            <div>
              <span>退出</span>
              <el-icon>
                <SwitchButton/>
              </el-icon>
            </div>
          </el-menu-item>
        </el-menu>
      </el-header>
      <el-container>
        <el-main style="padding-top: 0">
          <router-view></router-view>
        </el-main>
      </el-container>

    </el-container>
  </div>

  <el-dialog
      v-model="centerDialogVisible"
      title="视频通话"
      width="70%"
      align-center
  >
    <div>
      <video ref="localVideo"></video>
      <!--      <div class="remote">-->
      <!--        <img src="http://localhost:7000/common/file/loadFileId?fileId=c8806814-c4f3-44de-8e02-f26a7d8e7309">-->
      <!--      </div>-->
      <video ref="remoteVideo"></video>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="danger" @click="hang">
          挂断电话
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="isPhone"
      title="Warning"
      width="30%"
      align-center
  >
    <span>视频接听</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="refuse">拒绝</el-button>
        <el-button type="primary" @click="agree">
          同意
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import Peer from "peerjs";
import emitter from "../../utils/eventbus";
import {onMounted, ref} from 'vue'
import {clear, userInfo} from "../../utils/constant";
import {useRouter} from "vue-router";
import {callbacks, MessageDto, MessageType, send, SessionType, webSocket, webSocketLink} from "../../utils/webSocket";
import {error, message} from "../../utils/messageUtil";

const activeIndex2 = ref('')
const router = useRouter();
const url = ref(import.meta.env.VITE_APP_BASE_API + "/common/file/loadFileId?fileId=")

const showEnd = ref(true)

const centerDialogVisible = ref(false)
const isPhone = ref(false)
const localVideo = ref();
const remoteVideo = ref();
let localStream:MediaStream;
let peerId:string;
let peer:Peer;
//发起用户
let sendMessage:MessageDto;
//接受用户
let acceptMessage:MessageDto;

//挂断
const hang = ()=>{

  //关闭
  localStream.getTracks()[0].stop()
  localStream.getTracks()[1].stop()

  centerDialogVisible.value = false;

  //通知另外一方挂断
  if(sendMessage === null){
    //接收方
    let mes = {
      sendUserSocketDto: {
        userId: userInfo().id,
        name: userInfo().name
      },
      acceptUserSocketDto: {
        userId: acceptMessage.sendUserSocketDto.userId,
        name: acceptMessage.sendUserSocketDto.name
      },
      message: '',
      type: MessageType.HANGPHONE,
      sessionType: SessionType.ALONG
    }
    send(mes)
  }else{
    //发送方
    let mes = {
      sendUserSocketDto: {
        userId: userInfo().id,
        name: userInfo().name
      },
      acceptUserSocketDto: {
        userId: sendMessage.acceptUserSocketDto.userId,
        name: sendMessage.acceptUserSocketDto.name
      },
      message: '',
      type: MessageType.HANGPHONE,
      sessionType: SessionType.ALONG
    }
    send(mes)
  }
}

const refuse = ()=>{
  isPhone.value = false;
}

const agree=()=>{
  isPhone.value = false;
  centerDialogVisible.value = true;

  /**
   * 这个方法异步的 没去到流之前是没法进行call
   */
  getUserMedia({
    video:true,
    audio: true
  }).then((stream:any)=> {
    localStream = stream
    localVideo.value.srcObject = stream;
    localVideo.value.autoplay = true;
    localVideo.value.play();

    //视频通话
    let call =  peer.call(peerId, localStream)

    call.on('stream', function(remoteStream) {
      remoteVideo.value.srcObject = remoteStream;
      remoteVideo.value.autoplay = true;
    });
  })
}

onMounted(() => {

  webSocketLink(userInfo().id)

  userInfo().rolas.forEach(f => {
    if (f.roleName === '管理员') {
      showEnd.value = false;
    }
  })

  if(router.currentRoute.value.matched.map(u=>u.name).indexOf('center')!= -1){
    activeIndex2.value = '1'
  }

  if(router.currentRoute.value.matched.map(u=>u.name).indexOf('endcenter')!= -1){
    activeIndex2.value = '2'
  }

  if(router.currentRoute.value.matched.map(u=>u.name).indexOf('info')!= -1){
    activeIndex2.value = '0'
  }

  peer = new Peer();

  peer.on("open", Id=>{
    console.log("peer opend, the peerId is:", Id);

    peerId = Id

  })

  peer.on("close", () => {
    console.log("peer close....")
  })

  emitter.on("phone",msg=>{

    centerDialogVisible.value = true;

    getUserMedia({
      video:true,
      audio: true
    }).then((stream:any)=>{
      localStream = stream
      localVideo.value.srcObject = stream;
      localVideo.value.autoplay = true;
      localVideo.value.play();
    })

    let isCall = false;
    setTimeout(()=>{
      if(!isCall){
        //关闭
        localStream.getTracks()[0].stop()
        localStream.getTracks()[1].stop()
        centerDialogVisible.value = false;
        error("对方不接或者不在线")
      }
    }, 3000)

    peer.on('call', function(call) {
      isCall = true;
      call.answer(localStream);
      call.on('stream', function(remoteStream) {
        console.log(remoteStream);
        remoteVideo.value.srcObject = remoteStream;
        remoteVideo.value.autoplay = true;
      });
    });

    (msg as MessageDto).message = peerId
    send((msg as MessageDto))
    sendMessage = (msg as MessageDto);
  });

  callbacks.formPhone=(messageDto:MessageDto) => {
    isPhone.value = true;
    peerId = messageDto.message
    acceptMessage = messageDto
  }

  callbacks.phoneDown = (messageDto:MessageDto) => {
    //关闭
    localStream.getTracks()[0].stop()
    localStream.getTracks()[1].stop()
    centerDialogVisible.value = false;

    error(messageDto.sendUserSocketDto.name+'挂断了电话')
  }

  callbacks.RingDown=(messageDto:MessageDto) => {
    //关闭
    localStream.getTracks()[0].stop()
    localStream.getTracks()[1].stop()
    centerDialogVisible.value = false;

    error(messageDto.acceptUserSocketDto.name+'正在通话中')
  }
})



const handleSelect = (key: string, keyPath: string[]) => {

  activeIndex2.value = key

  if(key == '0'){
    router.push({
      name:'info',
      query:{
        userId:userInfo().id,
      }
    })
  }

  if (key === '2') {
    router.push({
      name: 'index'
    })
  }

  if (key === '1') {
    router.push({
      name: 'center'
    })
  }

  if (key === '4') {
    router.push({
      name: 'login'
    })
  }
}

function getUserMedia(constrains:any,success?:any,error?:any){
  if(navigator.mediaDevices.getUserMedia){
    return navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
  } else if ((navigator as any).webkitGetUserMedia){
    return  (navigator as any).webkitGetUserMedia(constrains).then(success).catch(error);
  } else if ((navigator as any).mozGetUserMedia){
    return  (navigator as any).mozGetUserMedia(constrains).then(success).catch(error);
  } else if ((navigator as any).getUserMedia){
    return  (navigator as any).getUserMedia(constrains).then(success).catch(error);
  }
}

</script>

<style scoped>
.flex-grow {
  flex-grow: 2;
}

.common-layout {
  display: flex;
  height: 100%;
}


video{
  width: 500px;
  height: 500px;
  margin: 0 20px;
}

.remote{
  display: inline-block;
  width: 500px;
  height: 500px;
  margin: 0 10px;
}

img{
  width: 500px;
  height: 500px;
}
</style>